package gson.emlog.adapter;

import gson.emlog.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class BlogsAdapter extends BaseAdapter {
	private JSONArray items;
	private Context mContext;

	public BlogsAdapter(JSONArray items, Context mContext) {
		super();
		this.items = items;
		this.mContext = mContext;
	}

	public int getCount() {
		return items.length();
	}

	public JSONObject getItem(int position) {
		try {
			return items.getJSONObject(position);
		} catch (JSONException e) {
			return null;
		}
	}

	public long getItemId(int position) {
		try {
			JSONObject obj = this.getItem(position);
			if (obj != null) {
				return obj.getInt("id");
			}
		} catch (JSONException e) {
			return position;
		}
		return position;
	}

	public int getReplyCount(int position) {
		try {
			JSONObject obj = this.getItem(position);
			if (obj != null) {
				return obj.getInt("cn");
			}
		} catch (JSONException e) {
			return position;
		}
		return -1;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		// 获取layout实例对象
		LayoutInflater lif = LayoutInflater.from(mContext);
		LinearLayout item = (LinearLayout) lif
				.inflate(R.layout.blogsitem, null);

		if (item != null) {
			try {
				JSONObject data = items.getJSONObject(position);
				// 赋值
				TextView title = (TextView) item.findViewById(R.id.blogtitle);
				title.setText(data.getString("t"));

				TextView rplCount = (TextView) item
						.findViewById(R.id.blog_cm_count);
				rplCount.setText("(" + data.getString("cn") + ")评论");

				TextView views = (TextView) item.findViewById(R.id.blog_views);
				views.setText("(" + data.getString("vs") + ")阅读");

				return item;
			} catch (JSONException e) {
				return convertView;
			}
		}

		return convertView;
	}
}
